package com.hcb.micro.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcb.micro.controller.base.BaseControllers;
import com.hcb.micro.dto.Manager;
import com.hcb.micro.service.IManagerService;
import com.hcb.micro.util.CommonUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("login")
public class LoginController extends BaseControllers{
	
	@Autowired
	IManagerService managerService;
	
	@RequestMapping(value = "tologin", method = RequestMethod.POST)
	@ResponseBody
	public String weixinLogin() throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		int right = 1;
		if (bodyInfo.get("username") == null || "".equals(bodyInfo.get("username"))) {
			right = 0;
		}else if(bodyInfo.get("password") == null || "".equals(bodyInfo.get("password"))) {
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}
		
		Manager manager = managerService.selectByName(bodyInfo.getString("username"));
		if(manager == null){
			json.put("result", "1");
			json.put("description", "账号不存在");
			return buildReqJsonObject(json);
		}
		String pwd = bodyInfo.getString("password");
		pwd = CommonUtil.strToMD5(pwd + bodyInfo.getString("username"));
		System.out.println(pwd);
		System.out.println(pwd);
		System.out.println(pwd);
		System.out.println(pwd);
		if(!manager.getPwd().equals(pwd)){
			json.put("result", "1");
			json.put("description", "密码错误");
			return buildReqJsonObject(json);
		}
		
		HttpSession session = request.getSession();
        session.setAttribute("MANAGER", manager);
        
        Map<String,Object> map = new HashMap<>();
        map.put("id", manager.getId());
        map.put("name", manager.getName());
        map.put("is_login", 1);
        
    	json.put("result", "0");
		json.put("description", "登陆成功");
		json.put("manager", map);
		return buildReqJsonObject(json);
	}
}
